<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>依赖注入</title>
</head>
<body>
  <div id="app">
    <my-first></my-first>
  </div>
</body>
<template id="first">
  <div>
    <h1>第一个组件</h1>
    <button @click="count++">加1</button> {{ count }}
    <my-second></my-second>
  </div>
</template>
<template id="second">
  <div>
    <h1>第二个组件 - {{ val }}</h1>
    <my-third></my-third>
  </div>
</template>
<template id="third">
  <div>
    <h1>第三个组件 - {{ val }} - {{ count }}</h1>
  </div>
</template>
<script src="../lib/vue.global.js"></script>
<script>
  const { computed } = Vue
  const Third = {
    template: '#third',
    inject: ['val', 'count']
  }
  const Second = {
    template: '#second',
    inject: ['val'],
    provide: {
      val: '传家宝2'
    },
    components: {
      MyThird: Third
    }
  }
  const First = {
    template: '#first',
    data () {
      return {
        val: '传家宝1',
        count: 10
      }
    },
    provide () {
      return {
        val: this.val,
        count: computed(() => this.count) // 确保后代的响应式
      }
    },
    components: {
      MySecond: Second
    }
  }
  Vue.createApp({
    components: {
      MyFirst: First
    }
  }).mount('#app')
</script>
</html>